package fr.poy.mygluco.client.ui;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog; 
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;

import fr.poy.mygluco.model.AppLog;
import fr.poy.mygluco.model.AppLogs;

public class MessageHandler extends Dialog{
	
	private static MessageHandler instance = new MessageHandler();
	public static MessageHandler get(){
		return instance;
	}
	
	private ContentPanel panel;
	
	private MessageHandler(){
		this.setHeading("Statut");
		this.setResizable(true);
		this.setConstrain(true);
		this.setMinimizable(false);
		this.setMaximizable(false);
		this.setClosable(false);
		this.setModal(true);
		this.setButtonAlign(HorizontalAlignment.CENTER);
		this.setHeight(220);
		this.setWidth(450); 
		this.setPlain(true);
		this.setFooter(true);
		this.setButtons(OK); 
		this.setHideOnButtonClick(true);

		this.setLayout(new FitLayout());

		panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setScrollMode(Scroll.AUTO);
		this.add(panel);
	}
	
	public void show(Object o) { 
		((Status)Registry.get("status")).clearStatus("")  ;
		if(o == null) return;
		panel.removeAll();
		//soit des logs
		//soit un seul log 
		if(o instanceof AppLogs){
			AppLogs logs = (AppLogs)o;
			if(logs.size()==0) return;
			if(logs.size()==1)
				((Status)Registry.get("status")).setText( logs.get(0).getLevel().toString() +" - "+ logs.get(0).getMessage() );
			else{  
				for (AppLog appLog : logs) {
					panel.addText("<div>" + appLog.toString() + "</div>");
				}
				//panel.addText("<div>" + logs.toString() + "</div>");
				this.show();
			}
		}else
		//soit une string
		if(o instanceof String){
			((Status)Registry.get("status")).setText( o.toString() ); 
		}else		
		//soit une exception
		if(o instanceof Throwable){
			panel.addText("<div style='color:red,font-size:14px;'>FATAL ! il y a soit un bug soit une erreur de communication serveur</div>");
			panel.addText("<div>" + ((Throwable)o).toString() + "</div>");
			this.show();
		}  
	}

}
